import { getPhone,setPhone, getIdCard, setIdCard,setUserInfo,setUserName } from "../../utils/store"
import IDValidator from "../../public/utils/idValid"
const Validator = new IDValidator()
// index.js
const app = getApp()
const {
  store
} = app;
Page({
  data: {
    baseUrl: app.globalData.baseUrl,
    phone:'',
    name:'',
    idCard: '',
    page: null,
    selectMode:1, //1登录 2注册
    intervalCountDown:null,
    countDownNum:60,
    yzm:'',
    isCanTapYzm:0 //0 可以 ，1不可以，2. 60s好了重新可以获取
  },
  // 事件处理函数
  onLoad(query) {
    console.log('query',query);
    this.setData({
      url: query.url,
      urlParams: query.urlParams
    })
  },
  submit(){

  },
  bindSetPhone(e){
    this.setData({
      'phone' : e.detail.value
    })
  },
  bindSetIdCard(e){
    this.setData({
      'idCard' : e.detail.value
    })
  },

  bindSetName(e){
    this.setData({
        'name' : e.detail.value
      })
  },

  changeMode(e){
    this.setData({
        'selectMode' : e.target.dataset.type
      })
  },

  //短信验证码
  sendMsg(){    
    const that = this;
    if(this.data.isCanTapYzm==0||this.data.isCanTapYzm==2){
        that.setData({
            isCanTapYzm:1,
            countDownNum:60
        })
        
        countDown()
    }
    function countDown(){
        that.setData({
            intervalCountDown:setInterval(()=>{
                if(that.data.countDownNum<=0){
                    clearInterval(that.data.intervalCountDown);
                    that.setData({
                        isCanTapYzm:2
                    })
              
                }
                that.setData({
                    countDownNum:that.data.countDownNum-1
                })
            },1000)
        }) 
    }
  },

  // 注册
  reg(){

    if(!/^1[3-9]\d{9}$/.test(this.data.phone)){
        wx.showToast({
            title: "请输入正确的手机号",
            icon: 'none',  
            duration: 3000
          });
        return 
    }

    if(!Validator.isValid(this.data.idCard)){
        wx.showToast({
            title: "请输入正确的身份证号",
            icon: 'none',  
            duration: 3000
          });
        return 
    }

    if(!this.data.name){
        wx.showToast({
            title: "请输入姓名",
            icon: 'none',  
            duration: 3000
          });
        return 
    }

    var that =this;
    wx.login({
      success: function (res) {
        if(res.code){
            wx.request({
                url: `${app.globalData.baseUrl}/v1/openApi/external/person/register/${res.code}`,
                method: 'POST',
                header: {
                  'Content-Type': 'application/json' // 请求头  
                },
                data:{
                    idCard:that.data.idCard,
                    phone:that.data.phone,
                    name:that.data.name
                },
                success(res) {
                    console.log('res',res);
                    if(res.data.code!=200){
                        wx.showToast({
                            title: res.data.msg,
                            icon: 'none',  
                            duration: 3000
                          });
                        return 
                    }

                    const userInfo = {
                        siocSapNo:that.data.idCard, //类似token的东西
                        siocCnName:that.data.name,    
                    }
                    wx.setStorageSync('userinfo', userInfo);
                    wx.reLaunch({
                        url: '/pages/bigMenu/bigMenu',
                      })
                }
            });
        }
      }
    })
  },


  backToLogin(){
    wx.reLaunch({
        url: '/pages/login/index',
      })
  },
  
validatemobile: function (mobile) {
  if (mobile.length !== 11) return false; // 长度校验
  const myreg = /^1[3-9]\d{9}$/; // 号段校验（支持13-19开头）
  return myreg.test(mobile);
},

  idLogin() {
    var that = this;
    var errMsg = "";
    if(!this.validatemobile(that.data.phone)){
      errMsg += "请输入正确手机号;";
    }
    if(that.data.name.length< 1){
      errMsg+="请输入正确姓名;";
    }
    if(that.data.idCard.length<1){
      errMsg+="请输入正确身份证号;";
    }
    if(errMsg){
      wx.showToast({ title: errMsg, icon: 'none' });
      return;
    }
    wx.request({
      url: that.data.baseUrl + '/staffInfo/wx/exLogin?name=' + that.data.name + '&idNo=' + that.data.idCard+ '&phone='+that.data.phone,
      method: 'GET',
      header: {
        'Content-Type': 'application/json' // 请求头  
      },
      success(res) {
        console.log('身份证登录响应:', res.data);
        var result = res.data;
        if (200 == result.code) {
          setUserInfo(result.data);
          setUserName(that.data.sapId);
          store.setState({
            userInfo: result.data
          });
          //二维码 或者其他由于需要登录重新定位的页面
          if (that.data.url && "undefined" != that.data.url) {
            console.log('that.data.url', that.data.url)
            console.log('that.data.urlParams', that.data.urlParams)
            wx.reLaunch({
              url: `/${that.data.url}?urlParams=${that.data.urlParams}`
            })
            return
          }
          wx.reLaunch({
            url: '/pages/menu2/menu2',
          });
          return;
        }else {
          wx.showModal({
            title: '提示',
            content: result.msg,
            showCancel: false
          })
        }
      }
    });

  },



  login(){
    var that =this;
    wx.login({
      success: function (res) {
        console.log('res',res.code);
        if(res.code){
            wx.request({
                url: `${app.globalData.baseUrl}/v1/openApi/external/person/login/${res.code}`,
                method: 'POST',
                header: {
                  'Content-Type': 'application/json' // 请求头  
                },
                data:{
                    idCard:that.data.idCard,
                    phone:that.data.phone
                },
                success(res) {
                    if(!res.data.data){
                        wx.showToast({
                            title: "登录失败",
                            icon: 'error',
                            duration: 3000
                          });
                          return
                    }
                    const userInfo = {
                        siocSapNo:res.data.data.idCard, //类似token的东西
                        siocCnName:res.data.data.name
                    }

                    wx.setStorageSync('userinfo', userInfo);
                    wx.reLaunch({
                        url: '/pages/bigMenu/bigMenu',
                      })
             
                }
              });
        
        }
      }
    })
    
  }
})